package com.zq.im;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.zq.im.bean.param.UnReceivedMessageIds;
import com.zq.im.fragment.FriendListFragment;
import com.zq.im.fragment.MeFragment;
import com.zq.im.fragment.MessageFragment;
import com.zq.im.im.JWebSocketClient;
import com.zq.im.im.JWebSocketClientService;
import com.zq.im.modle.ChatMessage;
import com.zq.im.modle.ChatMsg;
import com.zq.im.modle.DataContent;
import com.zq.im.modle.MsgActionEnum;
import com.zq.im.room.dao.MessageDao;
import com.zq.im.room.database.MyDataBase;
import com.zq.im.room.entity.Message;
import com.zq.im.utils.SharePreferenceUtils;
import com.zq.im.utils.Util;
import com.zq.im.view.CustomViewPager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    @BindView(R.id.viewPager)
    CustomViewPager mViewPager;

    @BindView(R.id.message)
    View message;

    @BindView(R.id.friend_list)
    View friendList;

    @BindView(R.id.me)
    View me;

    private Context mContext;
    private JWebSocketClient client;
    private JWebSocketClientService.JWebSocketClientBinder binder;
    private JWebSocketClientService jWebSClientService;

    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private FriendListFragment mFriendListFragment;
    private MessageFragment mMessageFragment;
    private MeFragment mMeFragment;
    private ChatMessageReceiver chatMessageReceiver;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initImmersionBar() {
        ImmersionBar.with(this)
                .barColor(R.color.white)
                .statusBarDarkFont(true)
                .init();
    }


    private class ChatMessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String onOpen = intent.getStringExtra("onOpen");
            /**
             * 第一次连接成 给服务端发送一个新消息,服务端用来保存 发送者的id,websocket 会建立长连接通道,并且会给这通道分配id,这个id和发送者id有关联
             * 要求:一个账号知识第一次连接服务器发送这个消息
             */
//            if (onOpen != null && onOpen.equals("onOpen")) {
//                ChatMsg chatMsg = new ChatMsg();
//                chatMsg.setMsg("");
//                chatMsg.setMsgId("");
//                chatMsg.setSenderId(SharePreferenceUtils.getString("userId"));
//
//                DataContent dataContent = new DataContent();
//                dataContent.setAction(MsgActionEnum.CONNECT.type);
//                dataContent.setChatMsg(chatMsg);
//                String msg = JSON.toJSONString(dataContent);
//
//                jWebSClientService.sendMessage(msg);
//                return;
//            }

            String messageStr = intent.getStringExtra("message");
            DataContent dataContentMsg = JSON.parseObject(messageStr, DataContent.class);

            ChatMsg chatMsg = dataContentMsg.getChatMsg();


            MessageDao messageDao = MyDataBase.getInstance(mActivity).getMessageDao();
            Message message = new Message(chatMsg.getMsgId(), chatMsg.getSenderId(), chatMsg.getReceiverId(), chatMsg.getMsg(),
                    chatMsg.getCreateDate());
            Disposable subscribe = messageDao.insert(message)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(() -> {
                        Log.d(TAG, "消息插入成功");
                    }, throwable -> {
                        Log.d(TAG, "消息插入失败");
                    });

            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setContent(dataContentMsg.getChatMsg().getMsg());
            chatMessage.setIsMeSend(0);
            chatMessage.setIsRead(1);
            chatMessage.setTime(dataContentMsg.getChatMsg().getCreateDate());

            //这里作为所有的消息的中转站,有的消息要刷新列表,有的消息要刷新进行通知,有的消息要...
            //聊天界面 展示消息,更新界面
            EventBus.getDefault().post(chatMessage);

        }
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.e("MainActivity", "服务与活动成功绑定");
            binder = (JWebSocketClientService.JWebSocketClientBinder) iBinder;
            jWebSClientService = binder.getService();
            client = jWebSClientService.client;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e("MainActivity", "服务与活动成功断开");
        }
    };

    @Override
    protected void initData() {
        super.initData();
        mContext = MainActivity.this;
        //启动服务
        startJWebSClientService();
        //绑定服务
        bindService();
        //注册广播
        doRegisterReceiver();
        //检测通知是否开启
        checkNotification(mContext);

        mMessageFragment = new MessageFragment();
        mFriendListFragment = new FriendListFragment();
        mMeFragment = new MeFragment();

        mFragments.add(mMessageFragment);
        mFragments.add(mFriendListFragment);
        mFragments.add(mMeFragment);

        EventBus.getDefault().register(this);
    }

    @Override
    protected void initView() {
        super.initView();
        mViewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setCurrentItem(0);
        mViewPager.setScroll(false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshFriendList(String message) {
        if (message.equals("refreshFriendList")) {
            mFriendListFragment.refreshFriendList(); //刷新列表
        } else {
            sendMessage(message); //发送消息
        }
    }

    /**
     * 消息已读
     *
     * @param ids
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getUnReceivedMessageIds(UnReceivedMessageIds ids) {
        ChatMsg chatMsg = new ChatMsg();
        chatMsg.setMsg("");
        chatMsg.setMsgId("");
        chatMsg.setSenderId(SharePreferenceUtils.getString("userId"));

        DataContent dataContent = new DataContent();
        dataContent.setAction(MsgActionEnum.SIGNED.type);
        dataContent.setChatMsg(chatMsg);
        dataContent.setExtand(ids.getUnReceivedMessageIds());
        String msg = JSON.toJSONString(dataContent);

        jWebSClientService.sendMessage(msg);
    }

    public void sendMessage(String msg) {
        if (client != null && client.isOpen()) {
            jWebSClientService.sendMessage(msg);
        } else {
            Util.showToast(mContext, "连接已断开，请稍等或重启App哟");
        }
    }


    @Override
    protected void setListener() {
        super.setListener();

        message.setOnClickListener(this);
        friendList.setOnClickListener(this);
        me.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.message:
                mViewPager.setCurrentItem(0);
                tabSelected(message);
                break;

            case R.id.friend_list:
                mViewPager.setCurrentItem(1);
                tabSelected(friendList);
                break;

            case R.id.me:
                mViewPager.setCurrentItem(2);
                tabSelected(me);
                break;

        }
    }

    private void tabSelected(View linearLayout) {
        message.setSelected(false);
        friendList.setSelected(false);
        me.setSelected(false);
        linearLayout.setSelected(true);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (selectList.size() > 0) {
                        LocalMedia localMedia = selectList.get(0);
                        mMeFragment.uploadImg(localMedia.getCutPath());
                    }
                    break;
            }
        }

    }

    private class MyAdapter extends FragmentPagerAdapter {

        MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();

    }

    /**
     * 绑定服务
     */
    private void bindService() {
        Intent bindIntent = new Intent(mContext, JWebSocketClientService.class);
        bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
    }

    /**
     * 启动服务（websocket客户端服务）
     */
    private void startJWebSClientService() {
        Intent intent = new Intent(mContext, JWebSocketClientService.class);
        startService(intent);
    }

    /**
     * 动态注册广播
     */
    private void doRegisterReceiver() {
        chatMessageReceiver = new ChatMessageReceiver();
        IntentFilter filter = new IntentFilter("com.xch.servicecallback.content");
        registerReceiver(chatMessageReceiver, filter);
    }

    /**
     * 获取通知权限,监测是否开启了系统通知
     *
     * @param context
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private boolean isNotificationEnabled(Context context) {

        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;

        Class appOpsClass = null;
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);

            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 检测是否开启通知
     *
     * @param context
     */
    private void checkNotification(final Context context) {
        if (!isNotificationEnabled(context)) {
            new AlertDialog.Builder(context).setTitle("温馨提示")
                    .setMessage("你还未开启系统通知，将影响消息的接收，要去开启吗？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            setNotification(context);
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            }).show();
        }
    }

    /**
     * 如果没有开启通知，跳转至设置界面
     *
     * @param context
     */
    private void setNotification(Context context) {
        Intent localIntent = new Intent();
        //直接跳转到应用通知设置的代码：
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            localIntent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            localIntent.putExtra("app_package", context.getPackageName());
            localIntent.putExtra("app_uid", context.getApplicationInfo().uid);
        } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
            localIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            localIntent.addCategory(Intent.CATEGORY_DEFAULT);
            localIntent.setData(Uri.parse("package:" + context.getPackageName()));
        } else {
            //4.4以下没有从app跳转到应用通知设置页面的Action，可考虑跳转到应用详情页面,
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                localIntent.setAction(Intent.ACTION_VIEW);
                localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
                localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
            }
        }
        context.startActivity(localIntent);
    }
}